<template>
  <section class="form">
    <section v-for="item in _fields" :key="item.key">
      <v-field ref="field" :type="item.type" :option="item.option" />
    </section>
  </section>
</template>
<script>
import VField from './field'
import { randomString } from '@/utils'
export default {
  name: 'Form',
  componentname: 'Form',
  components: { VField },
  props: {
    fields: {
      type: Array,
      default: [],
      required: true
    }
  },
  computed: {
    _fields() {
      return this.fields.map(a => {
        return {
          ...a,
          key: randomString(8)
        }
      })
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.on_event('change', (e) => {
        e.stopPropagation()
        this.$emit('change')
        /* if (e?.target?.type?.name === 'VRadio') {
          this.broadcast_event('radio-value-change', e)
        }*/
      })
    },

    getFields() {
      return this.$refs.field
    },

    getValue() {
      const r = {}
      return this.getFields().reduce((a, child) => {
        return a.then(() => {
          const name = child.option.name
          return Promise.resolve().then(() => child.getValue()).then(value => {
            r[name] = value
          })
        })
      }, Promise.resolve()).then(() => r)
    },

    setValue(data = {}) {
      return this.getFields().reduce((a, child) => {
        return a.then(() => {
          const name = child.option.name
          if (data.hasOwnProperty(name)) {
            return Promise.resolve().then(() => child.setValue(data[name]))
          }
        })
      }, Promise.resolve())
    },

    check() {
      let check = true
      return this.getFields().reduce((a, child) => {
        return a.then(() => {
          if (check) {
            return Promise.resolve().then(() => child.check()).then(result => {
              check = result
            })
          }
        })
      }, Promise.resolve()).then(() => check)
    }
  }
}
</script>
